from datetime import datetime
from typing import List, Dict, Optional
from models.config import LOTTERY_TYPES, DATA_DIR
from utils.common import save_to_csv, read_csv, ensure_data_dir

class LotteryDraw:
    """开奖数据模型"""
    def __init__(self, draw_number, draw_date, red_numbers, blue_number):
        self.draw_number = draw_number
        self.draw_date = draw_date
        self.red_numbers = red_numbers
        self.blue_number = blue_number

    def __str__(self):
        """返回彩票开奖信息的字符串表示"""
        base = f"期号: {self.draw_number}, 开奖日期: {self.draw_date}, 红球: {self.red_numbers}"
        if self.blue_number:
            return f"{base}, 蓝球: {self.blue_number}"
        return base

    def to_dict(self) -> Dict:
        """转换为字典格式"""
        return {
            'draw_number': self.draw_number,
            'draw_date': self.draw_date,
            'red_numbers': ','.join(self.red_numbers),
            'blue_number': self.blue_number
        }

    @classmethod
    def from_dict(cls, data: Dict) -> 'LotteryDraw':
        """从字典创建实例"""
        return cls(
            draw_number=data['draw_number'],
            draw_date=data['draw_date'],
            red_numbers=data['red_numbers'].split(','),
            blue_number=data['blue_number']
        )

class LotteryManager:
    """彩票数据管理器"""
    def __init__(self, lottery_type: str):
        if lottery_type not in LOTTERY_TYPES:
            raise ValueError(f"不支持的彩票类型: {lottery_type}")
        
        self.lottery_type = lottery_type
        self.config = LOTTERY_TYPES[lottery_type]
        self.data_file = f"{DATA_DIR}/{self.config['data_file']}"
        ensure_data_dir(DATA_DIR)

    def save_draw(self, draw: LotteryDraw) -> None:
        """保存开奖数据"""
        fieldnames = [
            'draw_number', 'draw_date', 'red_numbers', 
            'blue_number'
        ]
        save_to_csv([draw.to_dict()], self.data_file, fieldnames)

    def get_latest_draw(self) -> Optional[LotteryDraw]:
        """获取最新一期开奖数据"""
        draws = self.get_all_draws()
        if not draws:
            return None
        return draws[-1]

    def get_all_draws(self) -> List[LotteryDraw]:
        """获取所有开奖数据"""
        data = read_csv(self.data_file)
        return [LotteryDraw.from_dict(item) for item in data]

    def get_draw_by_date(self, date: str) -> Optional[LotteryDraw]:
        """根据日期获取开奖数据"""
        draws = self.get_all_draws()
        for draw in draws:
            if draw.draw_date == date:
                return draw
        return None

    def get_draw_by_number(self, draw_number: str) -> Optional[LotteryDraw]:
        """根据期号获取开奖数据"""
        draws = self.get_all_draws()
        for draw in draws:
            if draw.draw_number == draw_number:
                return draw
        return None 